
from fluentpython import FrenchDeck
from fluentpython import Vector

# 示例 1-1　一摞有序的纸牌
def example_1_1():
    deck = FrenchDeck()
    deck_0 = FrenchDeck()
    deck_clone = deck

    print(deck, deck_0, deck_clone)
    print(hex(id(deck.ranks)), hex(id(deck.suits)))
    print(hex(id(deck_0.ranks)), hex(id(deck_0.suits)))
    print(hex(id(deck_clone.ranks)), hex(id(deck_clone.suits)))
    #print(deck)
    #print(len(deck))
    #print("deck[0]=", deck[0], " deck[-1]=", deck[-1])

    from random import choice
    print(choice(deck))
    print(choice(deck))
    print(choice(deck))
    print(deck[:3])
    print(deck[12::13])

# 示例 1-2　一个简单的二维向量类
def example_1_2():
    v1 = Vector(2, 4)
    v2 = Vector(2, 1)
    print("\n", v1 + v2)
    v = Vector(3, 4)
    print(abs(v))
    print(v * 3)
    print(abs(v * 3))


# 列表推导（list comprehension）示例
def example_2_2_1():
    symbols = '$¢£¥€¤'
    codes = [ord(symbol) for symbol in symbols]
    print('codes=', codes)

# Notice: 列表推导也有可能被滥用。通常的原则是，只用列表推导来创建新的列表，
# 并且尽可能并保持简短。如果列表推导的代码超过了两行，可能就要考虑是不是得用
# for 循环重写了。

# 示例 2-7   把元组用作记录
def example_2_7():
    lax_coordinates = (33.9425, -118.408056)
    city, year, pop, chg, area = ('Tokyo', 2003, 32450, 0.66, 8014)
    travler_ids = [('USA', '31195855'), ('BRA', 'CE342567'),
                   ('ESP', 'XDA205856')]
    for passport in sorted(travler_ids):
        print('%s/%s' % passport)

    # for 循环可以分别提取元组里的元素，也叫作拆包（unpacking）。因为元组的
    # 第二个元素对我们没什么用，所以它赋值给“_”占位符
    for country, _ in travler_ids:
        print(country)

    import os
    _, filename = os.path.split('/home/luciano/.ssh/idrsa.pub')
    print(filename)

    # 用*来处理剩下的元素，平行赋值
    a, b, *rest = range(5)
    print(a, b, rest)
    a, b, *rest = range(3)
    print(a, b, rest)
    a, b, *rest = range(2)
    print(a, b, rest)

    # 在平行赋值中，* 前缀只能用在一个变量名前面，但是这个变量可以出现在赋值
    # 表达式的任意位置
    a, *body, c, d = range(5)
    print(a, body, c, d)
    *head, b, c, d = range(5)
    print(head, b, c, d)

# 示例 2-8  用嵌套元组来获取经度
def example_2_8():
    metro_areas = [
        ('Tokyo','JP',36.933,(35.689722,139.691667)), # ➊
        ('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)), 
        ('Mexico City', 'MX', 20.142, (19.433333, -99.133333)), 
        ('New York-Newark', 'US', 20.104, (40.808611, -74.020386)), 
        ('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635833)), 
    ]

    print('{:15} | {:^9} | {:^9}'.format('', 'lat.', 'long.')) 
    fmt = '{:15} | {:9.4f} | {:9.4f}' 
    for name, cc, pop, (latitude, longitude) in metro_areas: # ➋
        if longitude <= 0: # ➌
            print(fmt.format(name, latitude, longitude))
#➊ 每个元组内有 4 个元素，其中最后一个元素是一对坐标。
#➋ 我们把输入元组的最后一个元素拆包到由变量构成的元组里，这样就获取了坐标。
#➌ if longitude <= 0: 这个条件判断把输出限制在西半球的城市

example_2_8()